﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#if(NET35)
using LightFx.Linq.Expressions;
#endif
using System.Linq.Expressions;

namespace Orm.LinqParse
{
    /// <summary>
    /// 表达式toSQL字段
    /// </summary>
    internal class FieldNameTranslator : ExpressionVisitor
    {
        private List<string> filedNames;
        private bool _clearIgnoreAdd, _clearIgnoreUpdate;

        /// <summary>
        /// 得到属性。
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="clearIgnoreAdd"></param>
        /// <param name="clearIgnoreUpdate"></param>
        /// <returns></returns>
        public List<string> GetName(Expression expression, bool clearIgnoreAdd, bool clearIgnoreUpdate)
        {
            _clearIgnoreAdd = clearIgnoreAdd;
            _clearIgnoreUpdate = clearIgnoreUpdate;
            this.Visit(expression);
            return filedNames;
        }

#if(NET35)
        protected override Expression VisitMemberAccess(MemberExpression m)
#endif
#if(NET4)
        protected override Expression VisitMember(MemberExpression m)
#endif
        {
            if (m.Expression != null && m.Expression.NodeType == ExpressionType.Parameter)
            {
                if (filedNames == null)
                    filedNames = new List<string>();
                filedNames.Add(m.Member.Name);
                return m;
            }
            throw new NotSupportedException(string.Format("The member '{0}' is not supported", m.Member.Name));
        }
        /// <summary>
        /// 得到表达访问参数
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        protected override Expression VisitParameter(ParameterExpression p)
        {
            //如果表达式像 linq.Select(q=>q); 这样则选择所有字段。 
            var propLs = p.Type.GetProperties();
            filedNames = propLs.Select(i => i.Name).ToList();
            return p;
        }
    }
}
